import UIKit
import AddressBookUI

/// 对数据的处理, 
// 负责联系人获取, 修改,
class AddressBookKitHelp: NSObject {
    // 获取联系人
    static var addressBook: ABAddressBook?
    class func allContactsHelp(success: (contactArray: [Contact], error: NSError?)->Void) {
        var error:Unmanaged<CFErrorRef>?
        
        addressBook = ABAddressBookCreateWithOptions(nil, &error)?.takeRetainedValue()
        let currentStatus = ABAddressBookGetAuthorizationStatus()
        if currentStatus == .NotDetermined {
            ABAddressBookRequestAccessWithCompletion(addressBook, { (successfully, error) in
                dispatch_async(dispatch_get_main_queue(), {
                    if successfully {
                        //获取并遍历所有联系人记录
                        success(contactArray: self.readRecords(addressBook!), error: nil)
                        return
                    }
                    
                    success(contactArray: [], error: NSError(domain: "Unauthorized", code: 0, userInfo: [:]))
                })
            })
            
            return
        }
        
        if currentStatus == .Authorized {
            success(contactArray: readRecords(addressBook!), error: nil)
            return
        }
        
        let deniedError = NSError(domain: "Unauthorized", code:401, userInfo: [:])
        success(contactArray: [], error: deniedError)
    }
    
    class func readRecords(addressBook: ABAddressBook) -> [Contact] {
        let source = ABAddressBookCopyDefaultSource(addressBook).takeRetainedValue()
        let sysContacts = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, ABPersonSortOrdering(1)).takeRetainedValue() as NSArray
        
        var contactArray: [Contact] = []
        for contact in sysContacts {
            contactArray.append(Contact(contact: contact))
        }

        return contactArray
    }
    
    // 保存联系人
    class func saveAddressBookEmail(newContact: Contact, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>) {
        let dic = ABMultiValueCreateMutable(UInt32(kABMultiStringPropertyType)).takeRetainedValue()

        for (_, email) in newContact.contactEmails.enumerate() {
            ABMultiValueAddValueAndLabel(dic, email.email, "", nil)
        }
        
        ABRecordSetValue(newContact.contactRecord, kABPersonEmailProperty, dic, error)
        ABAddressBookSave(addressBook!, nil);
    }
}
